/* eslint-disable vue/no-setup-props-destructure */
import type { mapViewPropsType, mapViewStateType } from './typings'
import { defineComponent, onMounted, reactive } from 'vue'
import { useStore } from 'vuex'
import { ElLoading } from 'element-plus'
import { isPlainObject } from 'lodash'
import useAMap from '~/hooks/useAMap'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'MapView',
  props: ['id', 'orderMarker', 'needMultipleMarker', 'clickon', 'markers'],
  emits: ['changeAddress', 'clickMarker'],
  setup(props: mapViewPropsType, { emit, expose }) {
    const store = useStore()
    const { id = 'container' } = props
    const state = reactive<mapViewStateType>({
      currentMarker: undefined,
      markerList: []
    })

    // 获取租户设置的坐标
    const getCurrentTenant = useVuexGetters('user', ['userAddressInfo'])

    onMounted(() => {
      store.dispatch('user/GetCurrentTenant') // 获取租户设置的坐标
    })

    const loading = ElLoading.service({
      target: `#${id}`,
      lock: true,
      text: '加载中'
    })

    const [mapRef, aMapRef, amapIconRef] = useAMap(
      id,
      {
        center: [
          getCurrentTenant.userAddressInfo.value.lon,
          getCurrentTenant.userAddressInfo.value.lat
        ],
        zoom: 11
      },
      initAMap
    )

    // 添加marker点击事件 将储存的值发送给父元素
    const handleClickMarkerCallback = (e: { target: mapViewStateType['currentMarker'] }) => {
      emit('clickMarker', e?.target!?.getExtData?.())
    }

    // 清除标记点
    const handleClearAMapMarker = () => {
      if (props.needMultipleMarker) {
        mapRef.value.clearMap()
        return
      }
      if (state.currentMarker) mapRef.value.remove(state.currentMarker)
    }

    // 添加标点
    const handleAddAMapMarker = (
      lng: number,
      lat: number,
      item?: mapViewStateType['currentMarker']
    ) => {
      if (!props.needMultipleMarker) handleClearAMapMarker()
      const marker = new aMapRef.value.Marker({
        icon: amapIconRef.value,
        position: [lng, lat],
        offset: [-12, -22],
        // zooms: [2, 18],
        extData: item || {}
      })
      // .setExtDate(item || {})
      state.currentMarker = marker
      mapRef.value.add(marker)
      mapRef.value.setFitView()
      marker.on('click', handleClickMarkerCallback)
      if (props.needMultipleMarker) state.markerList.push(marker)
    }

    // 单击地图事件回调
    const handleClickAMapCallback = (mapsEvent: { lnglat: { lng: number; lat: number } }) => {
      const {
        lnglat: { lng, lat }
      } = mapsEvent
      handleAddAMapMarker(lng, lat)
      aMapRef.value.plugin(['AMap.Geocoder'], () => {
        const geocoder = new aMapRef.value.Geocoder({
          radius: 1000, // 以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
          extensions: 'all' // 返回地址描述以及附近兴趣点和道路信息，默认“base”
        })
        geocoder.getAddress(
          new aMapRef.value.LngLat(lng, lat),
          (status: string, result: { info: string; regeocode: { formattedAddress: string } }) => {
            if (status === 'complete' && result.info === 'OK') {
              const defectAddress = result.regeocode.formattedAddress
              const params = {
                latitude: lat,
                longitude: lng,
                defectAddress
              }
              emit('changeAddress', params)
            }
          }
        )
      })
    }

    // 根据props.markers来设置坐标点回调
    const handleSetMarkerByPropsMarkers = () => {
      if (props.markers && aMapRef.value) {
        const timer = setTimeout(() => {
          if (props.markers?.length) {
            props.markers!.forEach((item: mapViewStateType['currentMarker']) =>
              handleAddAMapMarker(item!?.lng, item!?.lat, item)
            )
          }
          if (isPlainObject(props.markers)) {
            const item = props.markers
            handleAddAMapMarker(
              (item as Record<string, any>)?.lng,
              (item as Record<string, any>)?.lat,
              item as any
            )
          }
          clearTimeout(timer)
        }, 0)
      }
    }

    // 初始化map事件
    function initAMap() {
      loading.close()
      const { clickon = false } = props
      if (clickon) mapRef.value.on('click', handleClickAMapCallback)
      if (props.markers && aMapRef.value) handleSetMarkerByPropsMarkers()
    }

    // onBeforeUnmount(async () => {
    //   await mapRef.value.destroy()
    // })
    expose({ mapRef, aMapRef, setMarkersByPropsMarkers: handleSetMarkerByPropsMarkers })
    return () => <section id={id}></section>
  }
})
